package com.yami.shop.security.api.service.impl;

import cn.hutool.core.util.StrUtil;
import com.yami.shop.config.WxConfig;
import com.yami.shop.security.api.service.AppLoginService;
import com.yami.shop.security.api.service.YamiUserDetailsService;
import com.yami.shop.security.comment.enums.App;
import com.yami.shop.security.comment.exception.WxErrorException;
import com.yami.shop.security.comment.model.AppConnect;
import com.yami.shop.security.comment.service.AppConnectService;
import com.yami.shop.security.comment.token.AuthenticationToken;
import lombok.AllArgsConstructor;
import me.chanjar.weixin.common.bean.WxOAuth2UserInfo;
import me.chanjar.weixin.common.bean.oauth2.WxOAuth2AccessToken;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;


/**
 * 微信公众号登陆
 * @author LGH
 */
@Component
@AllArgsConstructor
public class MpAppLoginServiceImpl implements AppLoginService {

    private final YamiUserDetailsService yamiUserDetailsService;

    private final WxConfig wxConfig;

    private final AppConnectService appConnectService;

    @Override
    public UserDetails loginAndGetUserDetails(AuthenticationToken authentication) {
        String code = authentication.getPrincipal();
        try {

            WxOAuth2AccessToken wxOAuth2AccessToken = wxConfig.getWxMpService().getOAuth2Service().getAccessToken(code);
            AppConnect appConnect = appConnectService.getByBizUserId(wxOAuth2AccessToken.getOpenId(), authentication.getAppType());
            if (appConnect == null) {
                appConnect = new AppConnect();

                WxOAuth2UserInfo wxOAuth2UserInfo = wxConfig.getWxMpService().getOAuth2Service().getUserInfo(wxOAuth2AccessToken, null);
                appConnect.setAppId(authentication.getAppType());
                appConnect.setNickName(wxOAuth2UserInfo.getNickname());
                appConnect.setImageUrl(wxOAuth2UserInfo.getHeadImgUrl());
                appConnect.setBizUserId(wxOAuth2UserInfo.getOpenid());
                appConnect.setBizUnionid(wxOAuth2UserInfo.getUnionId());
                appConnectService.save(appConnect);
            }
            return yamiUserDetailsService.loadUserByAppConnect(appConnect);
        } catch (me.chanjar.weixin.common.error.WxErrorException e) {
            throw new WxErrorException(e.getMessage());
        }
    }

    @Override
    public App getApp() {
        return App.MP;
    }
}
